package com.smt.filter;

import com.alibaba.fastjson.JSON;
import com.smt.common.BaseVo;
import com.smt.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 认证、返回指定类型
 *
 * @autor xiaoyu.fang
 * @date 2019/5/24 10:17
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 可以得到url
        String url = exchange.getRequest().getURI().toString();
        // 可以得到请求路径
        String address = exchange.getRequest().getRemoteAddress().toString();
        // 可以拿到token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (token == null) {
            // 从URL中获取
            token = exchange.getRequest().getQueryParams().getFirst("token");
            if (token == null) {
                // TODO 从body中获取参数
                
            }
        }
        log.info("url：{}, address：{}, token：{}", url, address, token);
        // 网关是非常重要的,在这里不让写过多代码,整个流程下来最好不要超过30ms，别的需要的数据可以自己根据需求去取
        ServerHttpResponse response = exchange.getResponse();
        // 通过校验
        if ("10086".equals(token)) {
            return chain.filter(exchange);
        }
        BaseVo baseVo = new BaseVo(ResultCode.UNAUTH.getCode(), ResultCode.UNAUTH.getInfo());
        byte[] datas = JSON.toJSONString(baseVo).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(datas);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
